<?php

require_once '../db_connect.php';
require_once '../models/user_cart.php';

class UserCartDAO {
    private $conn;

    public function __construct() {
        $this->conn = $GLOBALS['pdo'];
        if (!$this->conn) {
            die("Ошибка подключения к базе данных.");
        }
    }

    // Добавление новой записи в таблицу UserCart
    public function addUserCart(UserCart $userCart) {
        $query = "INSERT INTO UserCart (user_id, product_id, quantity) VALUES (?, ?, ?)";
        $stmt = $this->conn->prepare($query);
        $stmt->execute([$userCart->getUserId(), $userCart->getProductId(), $userCart->getQuantity()]);

        return $this->conn->lastInsertId();
    }

    // Получение записи по ID
    public function getUserCartById($id) {
        $query = "SELECT * FROM UserCart WHERE id = ?";
        $stmt = $this->conn->prepare($query);
        $stmt->execute([$id]);

        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($row) {
            return new UserCart(
                $row['id'],
                $row['user_id'],
                $row['product_id'],
                $row['quantity']
            );
        }

        return null;
    }

    // Обновление записи
    public function updateUserCart(UserCart $userCart) {
        $query = "UPDATE UserCart SET user_id = ?, product_id = ?, quantity = ? WHERE id = ?";
        $stmt = $this->conn->prepare($query);
        return $stmt->execute([
            $userCart->getUserId(),
            $userCart->getProductId(),
            $userCart->getQuantity(),
            $userCart->getId()
        ]);
    }

    // Удаление записи по ID
    public function deleteUserCart($id) {
        $query = "DELETE FROM UserCart WHERE id = ?";
        $stmt = $this->conn->prepare($query);
        return $stmt->execute([$id]);
    }

    // Метод для очистки корзины пользователя по userID
    public function clearCartByUserId($userId) {
        $query = "DELETE FROM UserCart WHERE user_id = ?";
        $stmt = $this->conn->prepare($query);
        $success = $stmt->execute([$userId]);

        return $success ? ['success' => true, 'message' => 'Корзина успешно очищена'] : ['success' => false, 'message' => 'Ошибка при очистке корзины'];
    }

    // Получение всех записей
    public function getAllUserCarts() {
        $query = "SELECT * FROM UserCart";
        $stmt = $this->conn->prepare($query);
        $stmt->execute();

        $userCartList = [];
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $userCartList[] = new UserCart(
                $row['id'],
                $row['user_id'],
                $row['product_id'],
                $row['quantity']
            );
        }

        return $userCartList;
    }

    public function getAllUserCartsJson() {
        $userCartList = $this->getAllUserCarts();
        $userCartArray = array_map(function($userCart) {
            return [
                'id' => $userCart->getId(),
                'user_id' => $userCart->getUserId(),
                'product_id' => $userCart->getProductId(),
                'quantity' => $userCart->getQuantity()
            ];
        }, $userCartList);
    
        return json_encode($userCartArray);
    }
    // Получение всех записей корзины по ID пользователя
    public function getUserCartByUserId($userId) {
        $query = "SELECT * FROM UserCart WHERE user_id = ?";
        $stmt = $this->conn->prepare($query);
        $stmt->execute([$userId]);

        $userCartList = [];
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $userCartList[] = new UserCart(
                $row['id'],
                $row['user_id'],
                $row['product_id'],
                $row['quantity']
            );
        }

        return $userCartList;
    }

    // Возвращение JSON-массива всех записей корзины по ID пользователя
    public function getUserCartByUserIdJson($userId) {
        $userCartList = $this->getUserCartByUserId($userId);
        $userCartArray = array_map(function($userCart) {
            return [
                'id' => $userCart->getId(),
                'user_id' => $userCart->getUserId(),
                'product_id' => $userCart->getProductId(),
                'quantity' => $userCart->getQuantity()
            ];
        }, $userCartList);

        return json_encode($userCartArray);
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['action']) && $_GET['action'] === 'getAllUserCartsJson') {
    $dao = new UserCartDAO();
    echo $dao->getAllUserCartsJson();
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['action']) && $_GET['action'] === 'getUserCartByUserIdJson' && isset($_GET['userId'])) {
    $userId = $_GET['userId'];
    $dao = new UserCartDAO();
    echo $dao->getUserCartByUserIdJson($userId);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'addUserCartFromCatalog') {
    $user_id = $_POST['user_id'];
    $dao = new UserCartDAO();
    $product_id = $_POST['product_id'];
    $quantity = isset($_POST['quantity']) ? intval($_POST['quantity']) : 1;

    $userCart = new UserCart(null, $user_id, $product_id, $quantity);
    $newId = $dao->addUserCart($userCart);

    echo json_encode(['success' => true, 'message' => 'Запись добавлена', 'newId' => $newId]);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['action']) && $_GET['action'] === 'deleteUserCart' && isset($_GET['id'])) {
    $id = $_GET['id'];
    $dao = new UserCartDAO();
    $success = $dao->deleteUserCart($id);
    if ($success) {
        echo json_encode(['success' => true, 'message' => 'Товар удалён из корзины']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Не удалось удалить товар из корзины']);
    }
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['action']) && $_GET['action'] === 'clearCartByUserId' && isset($_GET['userId'])) {
    $userId = $_GET['userId'];
    $dao = new UserCartDAO();
    $result = $dao->clearCartByUserId($userId);
    echo json_encode($result);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'deleteMultipleUserCarts' && !empty($_POST['ids'])) {
    $dao = new UserCartDAO();
    $ids = explode(',', $_POST['ids']);
    $errors = [];
    $successCount = 0;

    foreach ($ids as $id) {
        $success = $dao->deleteUserCart(trim($id));

        if ($success) {
            $successCount++;
        } else {
            $errors[] = ['id' => $id, 'message' => 'Не удалось удалить запись.'];
        }
    }

    if ($successCount > 0 && count($errors) === 0) {
        echo json_encode(['success' => true, 'message' => 'Все выбранные записи успешно удалены.']);
    } else {
        echo json_encode(['success' => false, 'errors' => $errors]);
    }
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['action']) && $_GET['action'] === 'getUserCartById' && isset($_GET['id'])) {
    $id = $_GET['id'];
    $dao = new UserCartDAO();
    $userCart = $dao->getUserCartById($id);

    if ($userCart) {
        echo json_encode([
            'id' => $userCart->getId(),
            'user_id' => $userCart->getUserId(),
            'product_id' => $userCart->getProductId(),
            'quantity' => $userCart->getQuantity()
        ]);
    } else {
        echo json_encode(['error' => 'Запись не найдена']);
    }
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['action'])) {
    $dao = new UserCartDAO();
    switch ($_GET['action']) {
        case 'updateUserCartQuantity':
            if (isset($_GET['id']) && isset($_GET['quantity'])) {
                $id = $_GET['id'];
                $quantity = $_GET['quantity'];
                $userCart = $dao->getUserCartById($id);
                if ($userCart) {
                    $userCart->setQuantity($quantity);
                    $success = $dao->updateUserCart($userCart);
                    if ($success) {
                        echo json_encode(['success' => true, 'message' => 'Корзина обновлена']);
                    } else {
                        echo json_encode(['success' => false, 'message' => 'Ошибка при обновлении корзины']);
                    }
                } else {
                    echo json_encode(['success' => false, 'message' => 'Товар в корзине не найден']);
                }
            } else {
                echo json_encode(['error' => 'Необходимые параметры не были предоставлены']);
            }
            break;
    }
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    error_log("Received action: " . $_POST['action']);
foreach ($_POST as $key => $value) {
    error_log("Key: $key; Value: $value");
}
    $dao = new UserCartDAO();
    switch ($_POST['action']) {
        case 'addUserCart':
            $user_id = $_POST['user_id'];
            $product_id = $_POST['product_id'];
            $quantity = $_POST['quantity'];

            $userCart = new UserCart(null, $user_id, $product_id, $quantity);
            $newId = $dao->addUserCart($userCart);

            echo json_encode(['success' => true, 'message' => 'Запись добавлена', 'newId' => $newId]);
            break;
        case 'updateUserCart':
            $id = $_POST['id'];
            $user_id = $_POST['user_id'];
            $product_id = $_POST['product_id'];
            $quantity = $_POST['quantity'];

            $userCart = new UserCart($id, $user_id, $product_id, $quantity);
            $success = $dao->updateUserCart($userCart);

            if ($success) {
                echo json_encode(['success' => true, 'message' => 'Запись обновлена']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Ошибка при обновлении записи']);
            }
            break;
    }
    exit();
}
?>